﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL = KC.Business.Stockmaster;

namespace KC.Presentation.Stockmaster
{
	public partial class graph : Form
	{
		public event EventHandler NeedsUpdate;

		public List<Newtonsoft.Json.Linq.JObject> ResultList = new List<Newtonsoft.Json.Linq.JObject>();
		public List<double> LastTradeValues = new List<double>();
		public DateTime nextReset = DateTime.MinValue;
		public string ticker, username, password;
		private int lastItemCount = 0, interval;
		
		public graph(string Ticker, int Interval, string Username, string Password)
		{
			CreateHandle();

			// These are used to pass to the buy/sell dialogs
			username = Username;
			password = Password;

			InitializeComponent();
			ticker = Ticker;
			Text = ticker.ToUpper();
			interval = Interval;

			timer1_Tick(null, null);
			timer1.Enabled = true;
			timer1.Interval = 1000;
			timer1.Start();

			// TODO: Add other chart lines here
			chart1.Series.Clear();
			chart1.ChartAreas.Clear();
			chart1.Series.Add("LastTrade");
			chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
			chart1.ChartAreas.Add("chart area");
		}
	
		public void RenderGraph()
		{
			try { if (chart1 == null || chart1.Series == null || chart1.Series.Count() == 0) return; }
			catch { return; } // should never happen, but does anyway
			chart1.Series[0].Points.Clear();
			for (int i=0; i < LastTradeValues.Count; i++) {
				chart1.Series[0].Points.AddXY(i, LastTradeValues[i]);
				chart1.Series[0].Points[i].AxisLabel = DateTime.Now.AddMilliseconds(- (LastTradeValues.Count - i) * interval).ToString("HH:mm:ss"); }
			chart1.ChartAreas[0].AxisX.ScaleBreakStyle.MaxNumberOfBreaks = 1;

			if (LastTradeValues.Count > 0) {
				chart1.ChartAreas[0].AxisY.Minimum = Math.Floor(LastTradeValues.Min()) - 1;
				chart1.ChartAreas[0].AxisY.Maximum = Math.Ceiling(LastTradeValues.Max()) + 1; }

		}
		public void RenderInfo()
		{
			if (ResultList.Count == 0)
				return;
			DataTable dt = new DataTable();
			dt.Columns.Add("key", typeof(string));
			dt.Columns.Add("value", typeof(string));
			//KeyNotFoundException
			try
			{
				foreach (var dyn in ((Newtonsoft.Json.Linq.JObject)(ResultList.Last())))
				{
					DataRow dr = dt.NewRow();
					dr["key"] = dyn.Key;
					dr["value"] = dyn.Value.ToString();
					dt.Rows.Add(dr);
				}
				label2.Text = "API Status: Everything is OK";
			}
			catch (KeyNotFoundException)
			{
				label2.Text = "API Status: API limit exceeded. Next limit reset: " + nextReset.ToString("MM/dd/yy HH:mm:ss");
			}
			dgvResult.DataSource = dt;
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			if (ResultList.Count > lastItemCount) {
				RenderGraph();
				RenderInfo();
				lastItemCount = ResultList.Count; }
		}

		private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			System.Diagnostics.Process.Start(@"http://apidocs.empireavenue.com/v1/get?call=profile/info");
		}

		private void btnReset_Click(object sender, EventArgs e)
		{
			ResultList.Clear();
			LastTradeValues.Clear();
			lastItemCount = 0;
			timer1_Tick(null, null);
		}

		private void btnBuy_Click(object sender, EventArgs e)
		{
			Buy buy = new Buy(username, password, ticker);
			if (buy.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				label2.Text = "Purchase successful! The graph will update shortly...";
		}

		private void btnSell_Click(object sender, EventArgs e)
		{
			// TODO: Sell
			throw new NotImplementedException();
		}

		private void btnProfile_Click(object sender, EventArgs e)
		{
			System.Diagnostics.Process.Start("http://www.empireavenue.com/" + ticker);
		}

		private void graph_FormClosing(object sender, FormClosingEventArgs e)
		{
			timer1.Tick -= timer1_Tick;
			timer1.Stop();
			timer1.Enabled = false;
			timer1.Dispose();
			Enabled = false;
		}
	}
}
